package com.mdlib.helper.module.location;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ljlib.core.util.LogUtil;
import com.ljlib.help.R;
import com.mdlib.helper.base.BaseTitleFragment;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.utils.ToastUtil;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

import static com.ljlib.help.R.string.finish;

/**
 * Created by librabin on 16/12/15.
 */

public class LocationFragment extends BaseTitleFragment implements LocationSource,
        AMapLocationListener, PoiSearch.OnPoiSearchListener, Inputtips.InputtipsListener {

    public static String EXTRA_KEYWORD = "extra_keyword";
    public static String EXTRA_CITY = "extra_city";


    @Bind(R.id.map)
    MapView mMapView;

    @Bind(R.id.address_edit)
    EditText mAddressField;

    @Bind(R.id.address_append_edit)
    EditText mAddressAppendField;

    @Bind(R.id.address_list_view)
    RecyclerView mRecyclerView;

    private AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);

    private boolean canSearch = false;

    private String mCityCode = "0516";


    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索

    private PoiResult poiResult; // poi返回的结果

    private int currentPage = 0;// 当前页面，从0开始计数


    private String mKeyword;
    private String mCity;
    private String type;
    private String buyType;

    private AddressEntity mAddressEntity;

    private AddressAdapter mAddressAdapter;


    private List<AddressEntity> mListdata = new ArrayList<>();

    public static LocationFragment newInstance(String keyword, String city, String type, String buyType) {
        LocationFragment fragment = new LocationFragment();
        Bundle args = new Bundle();
        args.putString(EXTRA_KEYWORD, keyword);
        args.putString(EXTRA_CITY, city);
        args.putString(UIHelper.MAP_TYPE, type);
        args.putString(UIHelper.BUY_TYPE, buyType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMapView.onCreate(savedInstanceState);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void initBundle(Bundle bundle) {
        super.initBundle(bundle);
        if (bundle != null) {
            mKeyword = bundle.getString(EXTRA_KEYWORD);
            mCity = bundle.getString(EXTRA_CITY);
            type = bundle.getString(UIHelper.MAP_TYPE);
            buyType = bundle.getString(UIHelper.BUY_TYPE);
            LogUtil.e("BUY_TYPE: " + buyType);
        } else {
            mCity = "海口";
            mKeyword = "";
        }

        mAddressEntity = new AddressEntity(0, 0, mKeyword, mCity, "0");

    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_location;
    }

    @Override
    protected void initView(View rootView) {
        super.initView(rootView);
        setCommonTitle(R.string.title_location_input)
                .setTvRightBg(finish)
                .setImgRightListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String extraAddr = mAddressAppendField.getText().toString();
                        String oneAddr = mAddressField.getText().toString();
                        if (TextUtils.isEmpty(oneAddr)) {
                            ToastUtil.showToast("请填写地址");
                            return;
                        } else {
                            mAddressEntity.setDetailAddress(oneAddr);
                        }
                        if (!TextUtils.isEmpty(extraAddr)) {
                            mAddressEntity.setExtraAddr(extraAddr);
                        }


                        Intent intent = new Intent();
                        intent.putExtra(MapActivity.EXTRA_ADDRESS_MAP, mAddressEntity);
                        intent.putExtra(UIHelper.MAP_TYPE, type);
                        getActivity().setResult(Activity.RESULT_OK, intent);
                        getActivity().finish();
                    }
                });
        init();

        mAddressAdapter = new AddressAdapter(mListdata);
//
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mAddressAdapter);
        mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity())
                .color(getActivity().getResources().getColor(R.color.material_gray_400))
                .sizeResId(R.dimen.currency_one).build());
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mAddressEntity = mListdata.get(position);

                mAddressField.setText(mAddressEntity.getDistrict() + mAddressEntity.getName());

            }
        });

        mAddressField.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (canSearch) {
                    String str = s.toString();
                    if (!TextUtils.isEmpty(str.trim())) {
                        mKeyword = str;
                        beginSearch(str);
                    }

                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }


    public void beginSearch(String keyword) {
        InputtipsQuery inputquery = new InputtipsQuery(keyword, mCity);
        Inputtips inputTips = new Inputtips(getActivity(), inputquery);
        inputTips.setInputtipsListener(LocationFragment.this);
        inputTips.requestInputtipsAsyn();

    }


    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String keyWord) {

        currentPage = 0;
        query = new PoiSearch.Query(keyWord, "", "海口");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        query.setCityLimit(true);

        poiSearch = new PoiSearch(getActivity().getApplicationContext(), query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }


    /**
     * 初始化
     */
    private void init() {
        if (aMap == null) {
            aMap = mMapView.getMap();
            if (mCity == null || TextUtils.isEmpty(mCity)) {
                mCity = "海口";
                mKeyword = "";
                setUpMap();
            } else {
                if (mKeyword == null || TextUtils.isEmpty(mKeyword)) {
                    mKeyword = "";
                }
                canSearch = true;
                mAddressField.setText(mKeyword);
                beginSearch(mKeyword);
            }
        }

        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        setupLocationStyle();
        startLoadingDialog(false);
    }


    private void setupLocationStyle() {
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.drawable.gps_point));
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(STROKE_COLOR);
        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(5);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(FILL_COLOR);
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
    }


    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
//                mLocationErrText.setVisibility(View.GONE);
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
                mCityCode = amapLocation.getCityCode();
                if (buyType.equals(UIHelper.TAKE)) {
                    mAddressField.setText(amapLocation.getAddress());
                    mAddressEntity.setDetailAddress(amapLocation.getAddress());
                    mAddressEntity.setLatitude(amapLocation.getLatitude());
                    mAddressEntity.setLongitude(amapLocation.getLongitude());
                }
                stopLoadingDialog();
                canSearch = true;

            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
//                mLocationErrText.setVisibility(View.VISIBLE);
//                mLocationErrText.setText(errText);
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(getActivity());
            mLocationOption = new AMapLocationClientOption();
            mLocationOption.setOnceLocation(true);
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {// 正确返回

            AddressEntity addressEntity;
            if (tipList.size() > 0) {
                mListdata.clear();
                for (int i = 0; i < tipList.size(); i++) {
                    addressEntity = new AddressEntity(
                            tipList.get(i).getPoint().getLatitude(),
                            tipList.get(i).getPoint().getLongitude(),
                            tipList.get(i).getName(),
                            tipList.get(i).getDistrict(),
                            tipList.get(i).getAdcode());
                    mListdata.add(addressEntity);
                    mRecyclerView.setVisibility(View.VISIBLE);
                }
                mAddressAdapter.notifyDataSetChanged();
            } else {
                mRecyclerView.setVisibility(View.GONE);
            }
        } else {
            ToastUtil.showToast("搜索出错了");
        }
    }

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
//        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
//            if (result != null && result.getQuery() != null) {// 搜索poi的结果
//                if (result.getQuery().equals(query)) {// 是否是同一条
//                    poiResult = result;
//                    // 取得搜索到的poiitems有多少页
//                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
//                    List<SuggestionCity> suggestionCities = poiResult
//                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
//
//                    if (poiItems != null && poiItems.size() > 0) {
//                        aMap.clear();// 清理之前的图标
//                        PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
//                        poiOverlay.removeFromMap();
//                        poiOverlay.addToMap();
//                        poiOverlay.zoomToSpan();
//                    } else if (suggestionCities != null
//                            && suggestionCities.size() > 0) {
//                        showSuggestCity(suggestionCities);
//                    } else {
//                        ToastUtil.show(PoiKeywordSearchActivity.this,
//                                R.string.no_result);
//                    }
//                }
//            } else {
//                ToastUtil.show(PoiKeywordSearchActivity.this,
//                        R.string.no_result);
//            }
//        } else {
//            ToastUtil.showerror(PoiKeywordSearchActivity.this, rCode);
//        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }


}
